<?php
namespace services;

class Http
{

    /**
     * GET
     *
     * @param $url 目标URL            
     * @param $parameters 参数(key=>value)
     *            return string
     */
    static public function get ($url, $parameters = array(), $header = [])
    {
        return self::request('GET', $url, $parameters, $header);
    }

    /**
     * POST
     *
     * @param $url 目标URL            
     * @param $parameters 参数(key=>value)
     *            return string
     */
    static public function post ($url, $parameters = array(), $header = [])
    {
        return self::request('POST', $url, $parameters, $header);
    }

    public static function request ($method, $url, $params, $header)
    {
        $str_params = http_build_query($params);
        $ch = curl_init();
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $str_params);
        } else{
            $url .= '?' . $str_params;
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//CURLOPT_SSL_VERIFYPEER：是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//CURLOPT_SSL_VERIFYHOST：是否检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_URL, $url);// CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//使用PHP curl获取页面内容或提交数据，有时候希望返回的内容作为变量储存，而不是直接输出。这个时候就必需设置curl的CURLOPT_RETURNTRANSFER选项为1或true。
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);//// 抓取URL并把它传递给浏览器
        //halt( $url);
        return $result;
    }

    public static function do_post_request ($url, $postdata, $data)
    {
        $str = "";
        foreach ($postdata as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $url = $url . '?' . rtrim($str, '&');//rtrim清除空格
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/octet-stream",
                "Content-length: " . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result);
    }
}
